package com.ticket.sass.admin.manager

import com.ticket.sass.admin.service.impl.*
import com.ticket.sass.admin.util.EscapeUtil
import com.ticket.sass.common.entity.tenant.OrderCommodityEntity
import com.ticket.sass.common.entity.tenant.OrderEntity
import com.ticket.sass.common.entity.tenant.enums.OrderCommodityStatus
import com.ticket.sass.common.entity.tenant.enums.OrderPayStatus
import com.ticket.sass.common.entity.tenant.enums.OrderPayType
import com.ticket.sass.common.exception.enums.ErrorCode
import com.ticket.sass.common.exception.exception.BadRequestException
import org.springframework.stereotype.Component

@Component
class OrderCommodityManager (
    private val orderManager: OrderManager,
    private val orderService: OrderServiceImpl,
    private val service: OrderCommodityServiceImpl,
    private val memberCardService: MemberCardServiceImpl
) {
    fun refund(order: OrderEntity, refundCoupon: Boolean) {
        order.id ?: throw BadRequestException(ErrorCode.RECORD_NOT_EXIST, ErrorCode.RECORD_NOT_EXIST.reasonPhrase)

        val orderCommodity: OrderCommodityEntity = service.getOneByOrderId(order.id)
        // 校验退单状态
        validateOrderStatus(orderCommodity, order)
        // 退优惠券
        if (refundCoupon)  orderManager.refundCoupon(order)

        // 退款
        if (order.payType == OrderPayType.CARD) {
            refundToCard(order)
        }
        order.payStatus = OrderPayStatus.REFUND_SUCCESS
        orderService.updateById(order)
    }

    private fun validateOrderStatus(orderCommodity: OrderCommodityEntity, order: OrderEntity) {
        when {
            orderCommodity.status == OrderCommodityStatus.REFUND_ING ||
            orderCommodity.status == OrderCommodityStatus.REFUND_SUCCESS ||
            order.payStatus == OrderPayStatus.REFUND_ING ||
            order.payStatus == OrderPayStatus.REFUND_SUCCESS -> {
                throw BadRequestException(
                    ErrorCode.BUSINESS_ERROR,
                    EscapeUtil.errorMessage("orderId", "订单已退")
                )
            }
        }
    }

    private fun refundToCard(order: OrderEntity) {
        val memberCard = memberCardService.getOneByUserId(order.userId)
        memberCardService.refundToCard(memberCard, order.payPrice)
        orderManager.saveTransactionRecord(order, memberCard)
    }
}